package com.jxb.first;

/**
 * 回文链表
 *
 * @author jiaobo
 * @date Created in 2024/12/8 21:55
 **/
public class PalindromeLinkedList_234 {

    public static void main(String[] args) {

    }

    //将单链表转成数组，然后通过双指针遍历，比较前后释放相等-时间复杂度O(n)，空间复杂度(o(n))
    public boolean isPalindrome(ListNode head) {
        //将单链表节点数据转成数组
        int length = 0;
        ListNode temp = head;
        while (temp != null) {
            length++;
            temp = temp.next;
        }
        int[] arr = new int[length];
        temp = head;
        int i =0;
        while (temp != null) {
            arr[i] = temp.val;
            temp = temp.next;
            i++;
        }

        int headP = 0;
        int lastP = length-1;
        for (int j = 0; j <length; j++) {
            if (arr[headP] != arr[lastP]) {
                return false;
            }
            headP++;
            lastP--;
        }
        return true;

    }

    public boolean isPalindrome1(ListNode head) {
        ListNode fastP = head;
        ListNode slowP = head;
        while (fastP != null && fastP.next != null) {
            fastP = fastP.next.next;
            slowP = slowP.next;
        }

        slowP = fanzhaun(slowP);
        fastP = head;

        while (slowP != null) {
            if (fastP.val != slowP.val) {
                return false;
            }
            fastP = fastP.next;
            slowP = slowP.next;
        }
        return true;
    }

    private ListNode fanzhaun(ListNode slowP) {
        ListNode pre = null;
        while (slowP != null) {
            ListNode next = slowP.next;
            slowP.next = pre;
            pre = slowP;
            slowP = next;
        }
        return pre;
    }

}
